const std = @import("std");

// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
    // 标准构建目标
    const target = b.standardTargetOptions(.{});

    // 标准构建模式
    // zig build -Doptimize=Debug Debug编译
    // zig build -Doptimize=Debug
    const optimize = b.standardOptimizeOption(.{});

    // 添加一个静态库构建
    const icelib = b.addStaticLibrary(.{
        .name = "icelib",
        // In this case the main source file is merely a path, however, in more
        // complicated build scripts, this could be a generated file.
        .root_source_file = b.path("src/icelib/icelib.zig"),
        .target = target,
        .optimize = optimize,
    });

    // 添加一个可执行程序构建
    const learn_exe = b.addExecutable(.{
        .name = "learn",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    // 添加到顶级 install step中作为依赖
    learn_exe.linkLibrary(icelib);
    // 添加到顶级 install step中作为依赖
    b.installArtifact(icelib);
    b.installArtifact(learn_exe);

    // zig 提供了一个方便的函数运行我们直接运行构建结果
    const run_cmd = b.addRunArtifact(learn_exe);

    // 注意：该步骤可选，显式声明运行依赖于构建
    // 这会使运行是从构建输出目录（默认为 zig-out/bin ）运行而不是构建缓存中运行
    // 不过，如果应用程序运行依赖于其他已存在的文件（例如某些 ini 配置文件）
    // 这可以确保它们正确的运行
    run_cmd.step.dependOn(b.getInstallStep());

    // 注意：此步骤可选
    // 此操作允许用户通过构建系统的命令传递参数，例如 zig build  -- arg1 arg2
    // 当前是将参数传递给运行构建结果
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    // 指定一个 step 为 run
    const run_step = b.step("run", "Run tests");
    run_step.dependOn(&run_cmd.step);

    // 构建一个单元测试的 Compile
    const lib_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/icelib/test_icelib.zig"),
        .target = target,
        .optimize = optimize,
    });
    lib_unit_tests.linkLibrary(icelib);
    const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);

    const exe_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

    // 构建一个 step，用于执行测试
    const test_step = b.step("test", "Run unit tests");

    // 测试 step 依赖上方构建的 run_exe_unit_tests
    test_step.dependOn(&run_lib_unit_tests.step);
    test_step.dependOn(&run_exe_unit_tests.step);
}
